package cn.topcode.controller;

import cn.topcode.beans.dto.Dto;
import cn.topcode.beans.pojo.User;
import cn.topcode.beans.pojo.UserLikeArticle;
import cn.topcode.beans.vo.articleVO.ArticleListSearchVO;
import cn.topcode.beans.vo.articleVO.ArticleListVO;
import cn.topcode.service.RpcArticleService;
import cn.topcode.service.RpcDirectoryService;
import cn.topcode.service.RpcUserLikeArticleService;
import cn.topcode.utils.Constants;
import cn.topcode.utils.DtoUtil;
import cn.topcode.utils.ValidationToken;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 文章相关功能controller
 */
@Controller
@RequestMapping("/article")
public class ArticleController {

    @Reference
    private RpcDirectoryService rpcDirectoryService;
    @Reference
    private RpcArticleService rpcArticleService;
    @Reference
    private RpcUserLikeArticleService rpcUserLikeArticleService;
    @Resource
    private ValidationToken validationToken;

    /***
     * 文章首页列表显示
     * @return
     */
    @ApiOperation(value = "文章首页列表显示", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "文章首页列表显示 ")
    @RequestMapping(value = "/articleIndex", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto articleIndex() {
        try {
            return DtoUtil.returnDataSuccess(rpcDirectoryService.findArticleTag());
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("查询失败", Constants.Article.QUERY_FAIL);
        }
    }

    /***
     * 文章列表查询
     * @param articleListSearchVO 查询条件
     * @return
     */
    @ApiOperation(value = "文章列表查询", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "文章列表查询 ")
    @RequestMapping(value = "/articleList", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto articleList(@RequestBody ArticleListSearchVO articleListSearchVO) {
        if (null == articleListSearchVO || null == articleListSearchVO.getTagFirst())
            return DtoUtil.returnFail("查询失败", Constants.Article.QUERY_FAIL);
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("tagFirst", articleListSearchVO.getTagFirst());
            map.put("tagSecond", null == articleListSearchVO.getTagFirst() ? null : articleListSearchVO.getTagSecond());
            map.put("tagThree", null == articleListSearchVO.getTagFirst() ? null : articleListSearchVO.getTagThree());
            List<ArticleListVO> list = rpcArticleService.findArticleByQuery(map);
            if (null == list.get(0))
                return DtoUtil.returnFail("暂无相关文章", Constants.Article.QUERY_ARTICLE_NOT);
            return DtoUtil.returnDataSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), Constants.SYSTEM_ERROR);
        }
    }

    /***
     * 根据文章id查询文章详情
     * @param articleId 文章ID
     * @return
     */
    @ApiOperation(value = "根据文章id查询文章", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "根据文章id查询文章 ")
    @RequestMapping(value = "/articleInfo/{articleId}", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto articleInfo(@PathVariable Integer articleId) {
        if (null == articleId || articleId == 0)
            return DtoUtil.returnFail("查询失败", Constants.Article.QUERY_FAIL);
        Map<String, Object> map = new HashMap<>();
        map.put("articleId", articleId);
        try {
            ArticleListVO articleListVO = rpcArticleService.findArticleByQuery(map).get(0);
            if (null == articleListVO)
                return DtoUtil.returnFail("暂无相关文章", Constants.Article.QUERY_ARTICLE_NOT);
            rpcArticleService.updateCount(articleId, articleListVO.getCount());
            return DtoUtil.returnDataSuccess(articleListVO);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), Constants.SYSTEM_ERROR);
        }
    }

    /***
     * 文章订阅
     * @param articleId 文章id
     * @param request
     * @return
     */
    @ApiOperation(value = "文章订阅", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "文章订阅 ")
    @RequestMapping(value = "/likes/{articleId}", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto likes(@PathVariable Integer articleId, HttpServletRequest request) {
        if (null == articleId || 0 == articleId)
            return DtoUtil.returnFail("没有获取相关文章id", Constants.Article.QUERY_FAIL);
        String token = request.getHeader("token");
        User user = validationToken.getCurrentUser(token);
        if (null != user) {
            Map<String, Object> map = new HashMap<>();
            map.put("uId", user.getUId());
            map.put("articleId", articleId);
            try {
                UserLikeArticle userLikeArticle = rpcUserLikeArticleService.findUserLikeArticleByQuery(map);
                Integer likes = rpcArticleService.findArticleByQuery(map).get(0).getLikes();
                if (null == userLikeArticle) {
                    userLikeArticle = new UserLikeArticle();
                    userLikeArticle.setUId(user.getUId());
                    userLikeArticle.setArticleId(articleId);
                    userLikeArticle.setStatus(1);
                    userLikeArticle.setCreateDate(new Date());
                    rpcUserLikeArticleService.addUserLikeArticle(userLikeArticle);
                    rpcArticleService.updateLikes(articleId, likes + 1);
                } else {
                    rpcUserLikeArticleService.updateUserLikeArticle(userLikeArticle);
                    if (userLikeArticle.getStatus() == 0) {
                        rpcArticleService.updateLikes(articleId, likes + 1);
                    } else {
                        rpcArticleService.updateLikes(articleId, likes - 1);
                    }
                }
                return DtoUtil.returnSuccess("修改订阅成功", rpcUserLikeArticleService.findUserLikeArticleByQuery(map).getStatus());
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail(e.getMessage(), Constants.SYSTEM_ERROR);
            }
        } else {
            return DtoUtil.returnFail("token失效，请重登录", Constants.User_AUTH.AUTH_TOKEN_INVALID);
        }
    }
}
